var index = 0
/*
currentModal == 0 申请modal申请人
currentModal == 1 表格人员
currentModal == 2 审核人/
 */
var currentModal = 0
/*
选择员工时目前激活的行/
 */
var currentRow = null

$(document).ready(function () {
    addTimeOutAction()
    //制表人
    $('#makeTablePerson').attr('value', window.localStorage.userID)
    $('#makeTablePerson').text(window.localStorage.userName)

    /*
      选择one员工/
       */
    $('.selectOneStaff-department-li img').on('click', function () {
        if($(this).parent().find('.hidden').length == 0){
            $(this).parent().find('.selectOneStaff-staff-ul').addClass('hidden')
            $(this).parent().find('.departmentName-img').attr('src', 'imgs/addition.png')
        }else{
            $(this).parent().find('.selectOneStaff-staff-ul').removeClass('hidden')
            $(this).parent().find('.departmentName-img').attr('src', 'imgs/offline.png')
        }
    })
    $('.selectOneStaff-department-li .departmentName-span').on('click', function () {
        if($(this).parent().find('.hidden').length == 0){
            $(this).parent().find('.selectOneStaff-staff-ul').addClass('hidden')
            $(this).parent().find('.departmentName-img').attr('src', 'imgs/addition.png')
        }else{
            $(this).parent().find('.selectOneStaff-staff-ul').removeClass('hidden')
            $(this).parent().find('.departmentName-img').attr('src', 'imgs/offline.png')
        }
    })
    /*
    按姓名搜索modal/
     */
    $('#myModal-selectOneStaff .modal-searchInput input').on('input propertychange', function () {
        if($(this).val() == ''){
            $('#form-selectOneStaff .selectOneStaff-staff-ul2').addClass('hidden')
            $('#form-selectOneStaff .selectOneStaff-department-ul').removeClass('hidden')
        }
    })
    /*
    表格初始化5行/
     */
    index = 0
    for(var i = 0; i < 5; i++){
        index++
        var tbody = $('.table-selfDefine tbody')
        var appendStr = "<tr class='table-tr'><td>" + index + "</td><td><input class='selectPerson' onclick='getAllStaff_one(1,this)' data-toggle='modal' data-target='#myModal-selectOneStaff'></td>" +
            "<td><input class='unitWage'></td><td><input class='days'></td><td class='sumWage'></td>" +
            "<td style='border-right: none'><a onclick='cleanRowApplyContent(this)'><img src='imgs/minus-r.png'></a></td></tr>"
        tbody.append(appendStr)
    }
    /*
    补助和天数改变事件/
     */
    $('.table-selfDefine').on('input', '.unitWage', function () {
        var unitWage = $(this).val()
        var days = $(this).parent().parent().find('.days').val()
        var sumWage = unitWage * days
        sumWage = sumWage.toFixed(2)
        $(this).parent().parent().find('.sumWage').text(sumWage)
    })
    $('.table-selfDefine').on('input', '.days', function () {
        var days = $(this).val()
        var unitWage = $(this).parent().parent().find('.unitWage').val()
        var sumWage = unitWage * days
        sumWage = sumWage.toFixed(2)
        $(this).parent().parent().find('.sumWage').text(sumWage)
    })
    /*
   小计改变事件/
    */
    $('.table-selfDefine').on('DOMNodeInserted', '.sumWage', function () {
        var tr = $('.table-selfDefine .table-tr')
        var totalWage = 0
        for(var i = 0; i < tr.length; i++){
            if(tr.eq(i).find('.sumWage').text()){
                totalWage = parseFloat(totalWage) + parseFloat(tr.eq(i).find('.sumWage').text())
            }
        }
        totalWage = totalWage.toFixed(2)
        $('#totalWage').text(totalWage)
    })
    /*
    搜索添加回车绑定事件/
     */
    $('#myModal-selectOneStaff .modal-searchInput input').on('keypress', function (event) {
        if(event.keyCode == '13'){
            searchOneByName_modal(this)
        }
    })

})
/*
提交外勤申请表/
 */
function submitApplyTable() {
    var date = $('#workDate').val()
    date = date.split(' ')[0]
    date = date.replace(/年/g, '/')
    date = date.replace(/月/g, '/')
    date = date.replace(/日/g, '')
    date = date.replace(/\//g, '-')

    var makeTablePerson = $('#makeTablePerson').attr('value')
    var department = $('#applyDepartment').attr('value')
    if(!department){
        alert('出勤部门不能为空！')
        return
    }
    var applayUser = $('#applyStaff').attr('value')
    if(!applayUser){
        alert('申请人不能为空！')
        return
    }
    var serviceCharge = $('#serviceCharge').val()
    if(!serviceCharge){
        alert('服务费不能为空！')
        return
    }
    var auditor = $('#auditor').attr('value')
    if(!auditor){
        alert('审核人不能为空！')
        return
    }
    var personNumber = $('#personNumber').text()
    if(!personNumber){
        alert('出勤人次不能为空！')
        return
    }
    var content = $('#content').val()

    var totalWage = $('#totalWage').text()
    if(!totalWage){
        alert('总计金额不能为空！')
        return
    }
    var tr = $('.table-selfDefine .table-tr')
    if(tr.length == 0){
        alert('请选择出勤人员！')
        return
    }
    var jsonArr = []
    for(var i = 0; i < tr.length; i++){
        var id = tr.eq(i).find('td').eq(1).find('.selectPerson').attr('value')
        if(i == 0){
            if(!id){
                alert('第一行人员不能为空！')
                return
            }
        }

        var json_ = {}
        if(id){
            json_['user'] = {
                "id": id
            }
            var unitWage = tr.eq(i).find('td').eq(2).find('input').val()
            json_['unitWage'] = parseFloat(unitWage).toFixed(2)
            var days = tr.eq(i).find('td').eq(3).find('input').val()
            json_['days'] = parseInt(days)
            var sumWage = tr.eq(i).find('td').eq(4).text()
            json_['sumWage'] = parseFloat(sumWage).toFixed(2)
            jsonArr.push(json_)
        }

    }
    var json = {
        "date":date,
        "personNum":personNumber,
        "totalWage":totalWage,
        "serviceCharge":parseFloat(serviceCharge).toFixed(2),
        "content":content,
        "applicant": {
            "id":applayUser
        },
        "auditor": {
            "id":auditor
        },
        "operator": {
            "id":makeTablePerson
        },
        "department": {
            "id":department
        },
        "details": jsonArr
    }
    let myjson = JSON.stringify(json)
    $.ajax({
        url: ipPort + '/temporaryProjectHeader/add',
        contentType: 'application/json',
        data: myjson,
        dataType: 'json',
        type: 'post',
        success: function (obj) {
            if(obj.code == 0){
                alert('提交成功！')
            }else {
                alert(obj.message)
            }
        },
        error: function (error) {
            console.log(error)
        }
    })

}
/*
人员改变事件/
 */
function changePerson() {
    var tr = $('.table-selfDefine .table-tr')
    var personNumber = 0
    for(var i = 0; i < tr.length; i++){
        var id = tr.eq(i).find('td').eq(1).find('.selectPerson').attr('value')
        if(id){
            personNumber++
        }
    }
    $('#personNumber').text(personNumber)
}
/*
增加申请表内容/
 */
function addApplyContent() {
    index++
    var tbody = $('.table-selfDefine tbody')
    var appendStr = "<tr class='table-tr'><td>" + index + "</td><td><input class='selectPerson' onclick='getAllStaff_one(1,this)' data-toggle='modal' data-target='#myModal-selectOneStaff'></td>" +
        "<td><input class='unitWage'></td><td><input class='days'></td><td class='sumWage'></td>" +
        "<td style='border-right: none'><a onclick='cleanRowApplyContent(this)'><img src='imgs/minus-r.png'></a></td></tr>"
    tbody.append(appendStr)
}
/*
清除申请表内容一行/
 */
function cleanRowApplyContent(thisObj) {
    $(thisObj).parent().parent().remove()
    index--
    var tr = $('.table-selfDefine').find('.table-tr')
    for(var i = 1; i <= tr.length; i++){
        tr.eq(i-1).find('td').eq(0).text(i)
    }
    changePerson()
}
/*
获取所有部门/
 */
function getAllDepartment() {
    $('#myModal-selectDepartment').modal('toggle')
    $('.selectDepartment-ul li').remove()
    $.ajax({
        url: ipPort + '/department/getAll',
        success:function (obj) {
            if(obj.code == 0){
                for(var j = 0; j < obj.data.length; j++){
                    var ul = $('.selectDepartment-ul')
                    var appendStr = '<li data-dismiss="modal" onclick="selectedOneDepartment(this)"><img src="imgs/tips_department_up.png" height="20px" style="margin-top: -2px;margin-right: 5px"><span ' + 'value="' + obj.data[j].id + '">' + obj.data[j].name + '</span></li>'
                    ul.append(appendStr)
                }
            }else{
                alert(obj.message)
            }
        },
        error:function (error) {
            console.log(error)
        }
    })
}
/*
选定部门/
 */
function selectedOneDepartment(thisObj) {
    $('#applyDepartment').val( $(thisObj).find("span").text())
    $('#applyDepartment').attr('value', $(thisObj).find("span").attr("value"))
}
/*************************************选取一个员工modal*****************************************/
/*
获取所有员工/
 */
function getAllStaff_one(str, thisObj = null) {
    currentRow = thisObj
    currentModal = str
    var staffInformationDepartmentA = $('.selectOneStaff-department-ul .selectOneStaff-department-li .departmentName-span')
    $.ajax({
        url:ipPort + '/department/getAll',
        dataType:'json',
        success:function (obj) {
            for(var i = 0; i < obj.data.length; i++){
                staffInformationDepartmentA.eq(i).parent().removeClass('hidden')
                staffInformationDepartmentA.eq(i).text(obj.data[i].name)
                staffInformationDepartmentA.eq(i).attr('value', obj.data[i].id)
                staffInformationDepartmentA.eq(i).parent().find('li').remove()
            }
            $.ajax({
                url:ipPort + '/user/getAll',
                dataType:'json',
                success:function (obj_) {
                    if(obj_.data.length != 0){
                        for(var j = 0; j < obj_.data.length; j++){
                            for(var m = 0; m < obj.data.length; m++){
                                if(obj_.data[j].department.id == obj.data[m].id){
                                    var staffUl = staffInformationDepartmentA.eq(m).parent().find('.selectOneStaff-staff-ul')
                                    var appendStr = '<li data-dismiss="modal" onclick="selectedOneStaff(this)"><img src="imgs/mine.png" height="20px" style="margin-top: -2px"><span ' + 'value="' + obj_.data[j].id + '">' + obj_.data[j].name + '</span></li>'
                                    staffUl.append(appendStr)
                                    break
                                }
                            }
                        }
                    }
                },
                error:function (error) {
                    console.log(error)
                }
            })
        },
        error:function (error) {
            console.log(error)
        }
    })
}
/*
通过姓名搜索/
 */
function searchOneByName_modal(thisObj) {
    var keyword = $(thisObj).parent().find('input').val()
    var type = $('#selectSearchOneWay-dropdownMenu').attr('value')
    if(keyword != ''){
        $.ajax({
            url:ipPort + '/user/search?type=' + type + '&keyword=' + keyword,
            dataType:'json',
            success:function (obj) {
                $('#form-selectOneStaff .selectOneStaff-department-ul').addClass('hidden')
                $('#form-selectOneStaff .selectOneStaff-staff-ul2').removeClass('hidden')
                var staffUl = $('#form-selectOneStaff').find('.selectOneStaff-staff-ul2')
                staffUl.find('li').remove()
                for(var i = 0; i < obj.data.length; i++){
                    var appendStr = '<li data-dismiss="modal" onclick="selectedOneStaff(this)"><img src="imgs/mine.png" height="20px" style="margin-top: -2px"><span ' + 'value="' + obj.data[i].id + '">' + obj.data[i].name + '</span></li>'
                    staffUl.append(appendStr)
                }
            },
            error:function (error) {
                console.log(error)
            }
        })
    }
}
/*
选定人员/
 */
function selectedOneStaff(thisObj) {
    if(currentModal == 0){
        $('#applyStaff').val( $(thisObj).find("span").text())
        $('#applyStaff').attr('value', $(thisObj).find("span").attr("value"))
    }
    else if(currentModal == 1){
        $(currentRow).val( $(thisObj).find("span").text())
        $(currentRow).attr('value', $(thisObj).find("span").attr("value"))

        changePerson()
    }
    else if(currentModal == 2){
        $('#auditor').val( $(thisObj).find("span").text())
        $('#auditor').attr('value', $(thisObj).find("span").attr("value"))
    }
}
/******************************************************************************/